package com.android.manghe.coupon.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import com.android.base.tools.BigDecimalUtils;
import com.android.base.view.recycler.BaseRecyclerViewAdapter;
import com.android.manghe.R;
import com.android.manghe.coupon.model.CouponRes;
import com.eightbitlab.rxbus.Bus;

import java.util.HashMap;
import java.util.List;

public class CouponAdapter extends BaseRecyclerViewAdapter<CouponRes.DataBean.CouponInfo, CouponAdapter.CouponHolder> {
    private Context mContext;
    private HashMap<String, Boolean> mSelectedMap = new HashMap<>();
    private CouponRes.DataBean.CouponInfo mSelectedItemObject;

    public CouponAdapter(Context context, List<CouponRes.DataBean.CouponInfo> list) {
        super(list);
        mContext = context;
    }

    public void update(List<CouponRes.DataBean.CouponInfo> list) {
        mSelectedMap.clear();
        CouponRes.DataBean.CouponInfo info;
        for (int i = 0; i < list.size(); i++) {
            info = list.get(i);
            mSelectedMap.put(info.id, i == 0);
            if(i == 0) {
                mSelectedItemObject = info;
            }
        }
        super.update(list);
    }

    public void selectedItem(CouponRes.DataBean.CouponInfo info) {
        for (int i = 0; i < getData().size(); i++) {
            mSelectedMap.put(getData().get(i).id, false);
        }
        if(info != null) {
            mSelectedMap.put(info.id, true);
            mSelectedItemObject = info;
        }
        notifyDataSetChanged();
    }

    public CouponRes.DataBean.CouponInfo getSelectedCoupon(){
        return mSelectedItemObject;
    }

    @Override
    protected void bindDataToItemView(CouponHolder holder, CouponRes.DataBean.CouponInfo item) {
        holder.setBackgroundResource(R.id.layoutCouponTick, mSelectedMap.get(item.id) ? R.mipmap.coupon_clicked : R.mipmap.coupon_nor);
        holder.setImageResource(R.id.ivCheckCoupon, mSelectedMap.get(item.id) ? R.mipmap.tick_click : R.mipmap.tick_normal);
        holder.setText(R.id.tvTickPrice, BigDecimalUtils.round(item.price,0));
        holder.setText(R.id.tvCoin, item.coin);
        holder.setOnClickListener(R.id.ivDetail, v -> {
            //显示详情
            Bus.INSTANCE.send(item);
        });
    }

    @Override
    public CouponHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
        return new CouponHolder(inflateItemView(viewGroup, R.layout.item_coupon));
    }

    public class CouponHolder extends BaseRecyclerViewAdapter.SparseArrayViewHolder {

        public CouponHolder(View itemView) {
            super(itemView);
        }
    }
}
